﻿using AutoMapper;
using B.S.BasicData.API.Write.Application.Command.Role;
using B.S.BasicData.Domain.Entities.UserRoleMenu;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;

namespace B.S.BasicData.API.Write.Application.Handler.Role
{
    /// <summary>
    /// 修改角色信息请求命令处理类
    /// </summary>
    public class UpdateRoleHandler:IRequestHandler<UpdateRoleCommand,ApiResult<int>>
    {
        IBaseRepository<RoleModel> roleRep;
        IMapper mapper;

        public UpdateRoleHandler(IBaseRepository<RoleModel> roleRep, IMapper mapper)
        {
            this.roleRep = roleRep;
            this.mapper = mapper;
        }

        public Task<ApiResult<int>> Handle(UpdateRoleCommand request, CancellationToken cancellationToken)
        {
            try
            {
                ApiResult<int> res = new ApiResult<int>();

                var role = roleRep.GetAll().Where(x => x.Id == request.id).FirstOrDefault();
                if (role == null)
                {
                    res.Msg = "角色信息不存在";
                    res.Code = ApiEnum.Fail;
                    return Task.FromResult(res);
                }

                var rolename = roleRep.GetAll().Where(x => x.RoleName == request.roleName && x.IsDeleted == false && x.Id != request.id).FirstOrDefault();
                if (rolename != null)
                {
                    res.Msg = "角色名称已存在";
                    res.Code = ApiEnum.Fail;
                    return Task.FromResult(res);
                }

                var entity = mapper.Map(request, role);
                entity.UpdateDate = DateTime.Now;
                entity.UpdateName ="李四";

                int r = roleRep.UpdateAsync(entity).Result;

                if (r > 0)
                {
                    res.Msg = "修改角色信息成功";
                    res.Data = r;
                    res.Code = ApiEnum.Success;
                }
                else
                {
                    res.Msg = "修改角色信息失败";
                    res.Code = ApiEnum.Fail;
                }

                return Task.FromResult(res);
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
